<style lang="less">
.pic{
    background: #AAA;
    font-size: 0;
    position: relative;

    img,
    video{
        position: relative;
        z-index: 1;

        width: 100%;
    }
    .poster{
        position: absolute;
        z-index: 2;
    }
    .circle-img {
        border-radius: 100%;
        z-index: 0
    }

    &.loaded{
        background: none;
    }

    .btn-play{
        height: 100%;
        width: 100%;
        position: absolute;
        left: 0;
        top: 0;
        z-index: 3;

        &:after{
            display: none;
            content: "";
            background: svg-load('../assets/icons/play.svg');
            background-size: cover;
            height: 120px;
            width: 120px;
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            pointer-events: none;
        }

        &.video:after{
            display: block;
        }
    }
}
</style>
<template>
    <div class="pic" :class="{loaded: loaded}" @click="onClick($event)">
        <img v-if="type == 'image'" :src="imageSrc" @load="onImageLoad" class="image" :class="{'circle-img': shape == 'circle'}">
        <img v-if="type == 'video'" :src="videoImageSrc" @load="onImageLoad" class="video">
        <div class="btn-play" :class="{
            video: type == 'video'
        }"></div>
    </div>
</template>
<script>
export default {
    props: {
        type: {
            type: String,
            default: 'image'
        },
        src: {
            type: String,
            required: true
        },
        shape: {
            type: String,
            default: 'rectangle'
        },
        // 仅仅视频有效
        // 如果不指定 poster，默认按七牛规则缩略图
        poster: {
            type: String,
            default: null
        },
        posterOffset: {
            type: Number,
            default: 0
        }
    },
    data() {
        return {
            loaded: false
        };
    },
    computed: {
        imageSrc() {
            return this.src;
        },
        videoImageSrc() {
            if(this.poster) {
                return this.poster;
            }

            const videoUrl = String(this.src).replace(/\?.+/, '');

            return videoUrl + '?vframe/jpg/offset/' + this.posterOffset;
        }
    },
    methods: {
        onClick(evt) {
            this.$emit('click', evt);
        },
        onVideoLoad() {
            this.onLoad();
        },
        onImageLoad() {
            this.onLoad();
        },
        onLoad() {
            this.loaded = true;

            this.$emit('loaded');
        }
    },
    watch: {
        src() {
            this.loaded = false;
        }
    }
};
</script>
